import store from "@/store/index.js"
import {getUrlParams} from '@/common/js/utils.js'


/* 
api地址
http://118.99.55.244:8822 https://tuyuyi.shop
*/
export const BASE_URL = ""

/* 
channel:getUrlParams("channel"),
invite_code:getUrlParams("invite_code") 
 */
// 统一POST请求
export const postApi = (url, data={})=>{
	let token = uni.getStorageSync("token") || ""
	let language = uni.getStorageSync("language") 
	return new Promise((resolve, reject)=>{
		uni.request({
			url:BASE_URL + url,
			method:"POST",
			timeout:10000,
			header:{
				token:token ,
				Language:language
			},
			data,
			success(res) {
				// 登录过期处理
				if(res.data.code === 401){
					store.commit("user/clearUserInfo")
					uni.navigateTo({
						url:"/pages/login/login"
					})
					reject(err)
				}else{
					resolve(res.data)
				}
			},
			fail(err) {
				reject(err)
			}
		})
	})
}

// 统一get请求
export const getApi = (url)=>{
	let token = uni.getStorageSync("token") || ""
	let language = uni.getStorageSync("language")
	return new Promise((resolve, reject)=>{
		uni.request({
			url:BASE_URL + url,
			method:"GET",
			timeout:10000,
			header:{
				token:token,
				Language:language
			},
			success(res) {
				// 登录过期处理
				if(res.data.code === 401){
					let token = uni.getStorageSync("token")
					store.commit("user/clearUserInfo")
					uni.navigateTo({
						url:"/pages/login/login"
					})
				}else{
					resolve(res.data)
				}
			},
			fail(err) {
				reject(err)
			}
		})
	})
}

// 上传文件接口
export const uploadFile = function(url, fileUrl, fileType="image"){
	let token = uni.getStorageSync("token") || ""
	let language = uni.getStorageSync("language")
	return new Promise((resolve, reject)=>{
		uni.uploadFile({
			url:BASE_URL + url,
			filePath:fileUrl,
			name:"file",
			fileType,
			header:{
				token:token,
				Language:language
			},
			success: (res)=> {
				 resolve(res.data)
			},
			fail(err){
				reject(err)
			}
		})
	})
}
